package com.threesome.memos.db;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import android.text.TextUtils;


public class MemoProvider extends ContentProvider {
	public static final String AUTHORITY = "com.threesome.memos.MemoProvider";
	private static final String DATABASE_NAME = "memos.db";
	private static final int DATABASE_VERSION = 1;
	
	private static final int MEMOS = 1;
	private static final int MEMOS_ID = 2;
	private static final UriMatcher sUriMatcher;
	static {
		sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
		sUriMatcher.addURI(AUTHORITY, "memos", MEMOS);
		sUriMatcher.addURI(AUTHORITY, "memos/#", MEMOS_ID);
	}

	@Override
	public boolean onCreate() {
		mOpenHelper = new DatabaseHelper(getContext());
		return true;
	}
	
	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		SQLiteDatabase db = mOpenHelper.getReadableDatabase();
		String orderBy;
		if (TextUtils.isEmpty(sortOrder)) {
			
			switch (sUriMatcher.match(uri)) {
			case MEMOS:
			case MEMOS_ID:
				orderBy = Memo.Columns.DEFAULT_SORT_ORDER;
				break;
			default:
				throw new IllegalArgumentException("Unknown URI " + uri);
			}
		} 
		else {
			orderBy = sortOrder;
		}
		Cursor c = null;
		switch (sUriMatcher.match(uri)) {
		case MEMOS:
			c = db.query(Memo.TABLE_NAME, projection, selection,
					selectionArgs, null, null, orderBy);
			break;
		case MEMOS_ID:
			c = db.query(Memo.TABLE_NAME, projection, Memo.Columns._ID + " = ?", 
					new String[] { uri.getPathSegments().get(1) }, null, null, sortOrder);
			break;
		default:
			throw new IllegalArgumentException("Unknown URI " + uri);
		}
		c.setNotificationUri(getContext().getContentResolver(), uri);
		return c;
	}

	@Override
	public String getType(Uri uri) {
		switch (sUriMatcher.match(uri)) {
		case MEMOS:
			return Memo.Columns.CONTENT_TYPE;
		case MEMOS_ID:
			return Memo.Columns.CONTENT_ITEM_TYPE;
		default:
			throw new IllegalArgumentException("Unknown URI " + uri);
		}
	}

	@Override
	public Uri insert(Uri uri, ContentValues initialValues) {
		int matchCode = sUriMatcher.match(uri);
		if (matchCode != MEMOS) {
			throw new IllegalArgumentException("Unknown URI " + uri);
		}

		ContentValues values;
		if (initialValues != null) {
			values = new ContentValues(initialValues);
		} else {
			values = new ContentValues();
		}
		
		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
		long rowId = db.insert(Memo.TABLE_NAME, null, values);
        if (rowId > 0) {
            Uri memoUri = ContentUris.withAppendedId(Memo.Columns.CONTENT_URI, rowId);
            getContext().getContentResolver().notifyChange(memoUri, null);
            return memoUri;
        }

        throw new SQLException("Failed to insert row into " + uri);
	}

	@Override
	public int delete(Uri uri, String where, String[] whereArgs) {
		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
		int count = 0;
		switch (sUriMatcher.match(uri)) {
		case MEMOS:
			count = db.delete(Memo.TABLE_NAME, where, whereArgs);
			break;
		case MEMOS_ID:
			String newsId = uri.getPathSegments().get(1);
			count = db.delete(Memo.TABLE_NAME, Memo.Columns._ID + "=" + newsId
                    + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
			break;
		default:
			throw new IllegalArgumentException("Unknown URI " + uri);
		}

		getContext().getContentResolver().notifyChange(uri, null);
		return count;
	}

	@Override
	public int update(Uri uri, ContentValues values, String where,
			String[] whereArgs) {
		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
		int count;
		switch (sUriMatcher.match(uri)) {
		case MEMOS:
			count = db.update(Memo.TABLE_NAME, values, where, whereArgs);
			break;
		case MEMOS_ID:
			String newsId = uri.getPathSegments().get(1);
			count = db.update(Memo.TABLE_NAME, values, Memo.Columns._ID + "=" + newsId
                    + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
			break;
		default:
			throw new IllegalArgumentException("Unknown URI " + uri);
		}

		getContext().getContentResolver().notifyChange(uri, null);
		return count;
	}

	private static class DatabaseHelper extends SQLiteOpenHelper {
		DatabaseHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL("CREATE TABLE " + Memo.TABLE_NAME + " ("
                    + Memo.Columns._ID + " INTEGER PRIMARY KEY,"
                    + Memo.Columns.MEMO_CONTENT_TYPE + " INTEGER,"
                    + Memo.Columns.MEMO_TRIGGER_TYPE + " INTEGER,"
                    + Memo.Columns.MEMO_REPEAT_TYPE + " INTEGER,"
                    + Memo.Columns.MEMO_STATUS + " INTEGER,"
                    + Memo.Columns.ALARM_CODE + " INTEGER,"
                    + Memo.Columns.MEMO_CONTENT + " TEXT,"
                    + Memo.Columns.MEMO_TRIGGER + " TEXT"
                    + ");");
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			db.execSQL("DROP TABLE IF EXISTS" + Memo.TABLE_NAME);
			onCreate(db);
		}
	}

	private static DatabaseHelper mOpenHelper;
}
